<template>
  <div class="com-quill-editor">
    <div class="example" v-show="isLoading || loading" :style="{ width: loadingbox.width + 'px', height: loadingbox.height + 'px', lineHeight: loadingbox.height + 'px' }"><a-spin/></div>
    <div v-show="false">
      <!-- 用于上传文件的组件 分别是图片 视频 音频 -->
      <a-upload
        action="#"
        :multiple="true"
        accept=".jpg,.jpeg,.png,.JPG,.JPEG"
        @change="uploadIng"
        :beforeUpload="handleUpload">
        <a-button id="upload">
          <a-icon type="upload" /> Click to Upload
        </a-button>
      </a-upload>
      <a-upload action="#" :multiple="true" accept=".mp4" @change="uploadIng" :beforeUpload="handleUpload1">
        <a-button id="upload1">
          <a-icon type="upload" /> Click to Upload
        </a-button>
      </a-upload>
      <a-upload action="#" :multiple="true" accept=".mp3,.ogg,.wav" @change="uploadIng" :beforeUpload="handleUpload2">
        <a-button id="upload2">
          <a-icon type="upload" /> Click to Upload
        </a-button>
      </a-upload>
    </div>
    <quill-editor
      class="remove70"
      style="height: 400px; margin-bottom: 70px; padding-bottom: 10px"
      :options="editorOption"
      v-model="content"
      @blur="btnBlur"
      @change="onEditorChange"
      ref="QuillEditor">
    </quill-editor>
    <span class="sizeNumber" v-if="isLimitNumber">当前输入字数：{{ currentNumber }} / {{ isLimitNumber }}</span>
    <video style="opacity: 0;width:100%;position:absolute;" width="100%" id="myvideo"></video>
  </div>
</template>

<style>
  /* .example{
    position: absolute;
    background-color: rgba(255, 255, 255, 0.8);
    width: 100%;
    height: 100px;
    text-align: center;
  } */
  .el-icon-video-play {
    font-size: 20px;
    font-weight: 800;
  }

  .ql-toolbar.ql-snow .ql-formats {
    margin: 0;
  }

  .editor {
    line-height: normal !important;
    height: 500px;
  }

  .ql-snow .ql-tooltip[data-mode="link"]::before {
    content: "请输入链接地址:";
  }

  .ql-snow .ql-tooltip.ql-editing a.ql-action::after {
    border-right: 0px;
    content: "保存";
    padding-right: 0px;
  }

  .ql-snow .ql-tooltip[data-mode="video"]::before {
    content: "请输入视频地址:";
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item::before {
    content: "14px";
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value="small"]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="small"]::before {
    content: "10px";
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value="large"]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="large"]::before {
    content: "18px";
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value="huge"]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="huge"]::before {
    content: "32px";
  }

  .ql-snow .ql-picker.ql-header .ql-picker-label::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item::before {
    content: "文本";
  }

  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="1"]::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="1"]::before {
    content: "标题1";
  }

  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="2"]::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="2"]::before {
    content: "标题2";
  }

  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="3"]::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="3"]::before {
    content: "标题3";
  }

  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="4"]::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="4"]::before {
    content: "标题4";
  }

  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="5"]::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="5"]::before {
    content: "标题5";
  }

  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="6"]::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="6"]::before {
    content: "标题6";
  }

  .ql-snow .ql-picker.ql-font .ql-picker-label::before,
  .ql-snow .ql-picker.ql-font .ql-picker-item::before {
    content: "标准字体";
  }

  .ql-snow .ql-picker.ql-font .ql-picker-label[data-value="serif"]::before,
  .ql-snow .ql-picker.ql-font .ql-picker-item[data-value="serif"]::before {
    content: "衬线字体";
  }

  .ql-snow .ql-picker.ql-font .ql-picker-label[data-value="monospace"]::before,
  .ql-snow .ql-picker.ql-font .ql-picker-item[data-value="monospace"]::before {
    content: "等宽字体";
  }
  .example {
    position: absolute;
    text-align: center;
    background: rgba(255, 255, 255, 0.65);
    border-radius: 4px;
    margin-bottom: 20px;
    /* padding: 30px 50px; */
    margin: 20px 0;
    z-index: 999;
  }
</style>

<script>
  import {
    btnUpload,
    uuid,
    getTime,
    extname,
    btnUpload3
  } from '@/utils/upload'
  import {
    UploadOutlined
  } from '@ant-design/icons-vue'
  import {
    quillEditor,
    Quill
  } from 'vue-quill-editor'
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'
  import AudioBlot from '@/utils/richText.js' // 引入解决音频js
  import {
    addQuillTitle
  } from '@/utils/quill_title.js'
  // 音视频图片上传接口
  import {
    btnReturnToken,
    btnSignature
  } from '@/api/upload'
  import { message } from 'ant-design-vue'
  Quill.register(AudioBlot)
  // 工具栏配置

  const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'], // toggled buttons
    ['blockquote', 'code-block'],

    [{
      header: 1
    }, {
      header: 2
    }], // custom button values
    [{
      list: 'ordered'
    }, {
      list: 'bullet'
    }],
    [{
      script: 'sub'
    }, {
      script: 'super'
    }], // superscript/subscript
    [{
      indent: '-1'
    }, {
      indent: '+1'
    }], // outdent/indent
    [{
      direction: 'rtl'
    }], // text direction

    [{
      size: ['small', false, 'large', 'huge']
    }], // custom dropdown
    [{
      header: [1, 2, 3, 4, 5, 6, false]
    }],

    [{
      color: []
    }, {
      background: []
    }], // dropdown with defaults from theme
    [{
      font: []
    }],
    [{
      align: []
    }],
    ['link', 'image', 'video'],
    ['voice'],
    ['clean'] // remove formatting button
  ]

  export default {
    name: 'RichText',
    props: {
      isLimitNumber: {
        type: Number,
        default: 5000,
        required: false
      },
      value: {
        type: String,
        default: ''
      },
      loading: {
        type: Boolean,
        default: () => false
      },
      editContent: {
        type: String,
        default: () => ''
      }
    },
    components: {
      UploadOutlined,
      quillEditor
    },
    data () {
      return {
        isLoading: false,
        loadingbox: {
          width: '',
          height: ''
        },
        verifyParams: {
          loading: false,
          disabled: false
        },
        content: '',
        fullscreenLoading: false,
        editorOption: {
          placeholder: '请在这里输入',
          modules: {
            toolbar: {
              container: toolbarOptions, // 工具栏
              handlers: {
                image: function (value) {
                  if (value) {
                    document.querySelector('#upload').click()
                  } else {
                    this.quill.format('image', false)
                  }
                },
                video: function (value) {
                  if (value) {
                    document.querySelector('#upload1').click()
                  } else {
                    this.quill.format('video', false)
                  }
                },
                voice: function (value) {
                  if (value) {
                    document.querySelector('#upload2').click()
                  } else {
                    this.quill.format('voice', false)
                  }
                }
              }
            }
          },
          initVoiceButton: function () {
            // 初始化"voice"按钮样式
            // 添加elment-ui图标
            const voiceButton = document.querySelector('.ql-voice')
            voiceButton.innerHTML =
              `<svg focusable="false" class="" data-icon="audio" width="1.15em" height="1em" fill="currentColor" aria-hidden="true" viewBox="64 64 896 896"><path d="M842 454c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8 0 140.3-113.7 254-254 254S258 594.3 258 454c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8 0 168.7 126.6 307.9 290 327.6V884H326.7c-13.7 0-24.7 14.3-24.7 32v36c0 4.4 2.8 8 6.2 8h407.6c3.4 0 6.2-3.6 6.2-8v-36c0-17.7-11-32-24.7-32H548V782.1c165.3-18 294-158 294-328.1zM512 624c93.9 0 170-75.2 170-168V232c0-92.8-76.1-168-170-168s-170 75.2-170 168v224c0 92.8 76.1 168 170 168zm-94-392c0-50.6 41.9-92 94-92s94 41.4 94 92v224c0 50.6-41.9 92-94 92s-94-41.4-94-92V232z"></path></svg>`
            // voiceButton.title = "音频"
          }
        },
        currentNumber: 0
      }
    },
    mounted () {
      if (this.editContent) this.content = this.editContent
      this.$nextTick(() => {
        addQuillTitle()
        this.currentNumber = this.$refs.QuillEditor.quill.getLength() - 1
        this.editorOption.initVoiceButton()
        this.loadingbox.width = document.getElementsByClassName('com-quill-editor')[0].offsetWidth
        this.loadingbox.height = document.getElementsByClassName('com-quill-editor')[0].offsetHeight
      })
    },
    watch: {
      value (n) {
        this.content = n
      },
      content (n) {
        this.$emit('change', n)
      }
    },
    methods: {
      init (data) {
        this.content = data
        this.currentNumber = this.$refs.QuillEditor.quill.getLength() - 1
      },
      btnBlur () {
        this.$emit('btnGetTxt', this.content)
      },
      onEditorChange (event) {
        if (this.isLimitNumber) {
          this.currentNumber = event.quill.getLength() - 1
          event.quill.deleteText(this.isLimitNumber, 1)
        }
        this.$emit('btnGetTxt', this.content)
      },
      // 上传时显示loading
      uploadIng () {
        this.fullscreenLoading = true
      },
      handleUpload (file) {
        // 校验文件
        if (file.size / 1024 / 1024 > 15) {
          const isRightSize = file.size / 1024 / 1024 < 15
          message.warning('文件大小超过 3MB')
          return isRightSize
        } else {
          this.isLoading = true
          // 上传
          const hz = extname(file.name) // 后缀
          const sname = uuid(32, 32) // 随机名
          const from = {
            file_name: 'pc/goodsAdmin/addGoods/' + getTime() + '/' + sname + '.' + hz
          }
          btnReturnToken(from).then((res) => {
            const yname =
              'pc/goodsAdmin/addGoods/' + getTime() + '/' + sname + '.' + hz
            btnUpload(file, yname, res.upload_token)
              .then((res) => {
                this.isLoading = false
                message.success('上传成功')
                this.fullscreenLoading = false
                // 获取富文本组件实例
                const quill = this.$refs.QuillEditor.quill
                // 获取光标所在位置
                const length = quill.getSelection().index
                // 插入图片，res为服务器返回的图片链接地址
                // quill.insertEmbed(length, 'image', `https://img.tokenbty.com/${res}`)
                quill.insertEmbed(length, 'image', res)
                // 调整光标到最后
                quill.setSelection(length + 1)
              })
              .catch((err) => {
                this.isLoading = false
                message.error(err)
              })
          }).catch((err) => {
            this.isLoading = false
            message.error(err)
          })
        }
        return false
      },
      // 上一个函数返回值传入转Blob
      dataURLtoBlob (dataurl) {
        return new Promise(function (resolve) {
          var arr = dataurl.split(',')
          var mime = arr[0].match(/:(.*?);/)[1]
          var bstr = atob(arr[1])
          var n = bstr.length
          var u8arr = new Uint8Array(n)
          while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
          }
          resolve(new Blob([u8arr], {
            type: mime
          }))
        })
      },
      // Blob，自定义图片名称 传入得到 图片文件流
      blobToFile (theBlob, fileName) {
        return new Promise(function (resolve) {
          theBlob.lastModifiedDate = new Date()
          theBlob.name = fileName
          resolve(theBlob)
        })
      },
      handleUpload1 (file) {
        // 校验文件
        if (file.size / 1024 / 1024 > 15) {
          const isRightSize = file.size / 1024 / 1024 < 15

          if (!isRightSize) {
            message.warning('文件大小超过 15MB')
          }
          return isRightSize
        } else {
          const from = {
            ClassId: process.env.NODE_ENV === 'production' ? 753706 : 790574
          }
          this.isLoading = true
          btnSignature(from).then((res) => {
            const getSignature = res.signature
            btnUpload3(getSignature, file).then((data) => {
              var video = document.getElementById('myvideo')
              video.src = data.url
              var canvas = document.createElement('canvas')
              canvas.id = 'myCanvas'
              const ctx = canvas.getContext('2d')
              video.crossOrigin = 'anonymous' // 解决跨域问题，也就是提示污染资源无法转换视频
              video.currentTime = 1 // 第一秒
              setTimeout(() => {
                video.oncanplay = () => {
                  canvas.width = video.videoWidth // 获取视频宽度
                  canvas.height = video.videoHeight // 获取视频高度
                  // 利用canvas对象方法绘图
                  ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight)
                  // 转换成base64形式
                  const imgsrc = canvas.toDataURL('image/png') // 截取后的视频封面
                  this.dataURLtoBlob(imgsrc).then((res1) => {
                    this.blobToFile(res1, 'cover').then((res3) => {
                      const imgSname = uuid(32, 32) // 随机名
                      const imgForm = {
                        file_name: 'pc/NewAds/img/' + getTime() + '/' + imgSname + '.png'
                      }
                      btnReturnToken(imgForm)
                        .then((resp) => {
                          const imgYname = 'pc/NewAds/img/' + getTime() + '/' + imgSname + '.png'
                          btnUpload(res3, imgYname, resp.upload_token)
                            .then((response) => {
                              // 获取富文本组件实例
                              const quill = this.$refs.QuillEditor.quill
                              // 获取光标所在位置
                              const length = quill.getSelection().index
                              // 插入图片，res为服务器返回的图片链接地址
                              quill.insertEmbed(length, 'video', `${data.url}?${response}`)
                              // this.content = insertStr(this.content, length + 1, `<video style="margin: 0 auto" width="300px" src="${res}" controls="controls"></video>`)
                              // this.content = this.insertStr(this.content, length + 1, `<iframe src="${data.url}" poster='${response}' scrolling="no" border="0" frameBorder="no" framespacing="0" allowFullScreen="true"></iframe>`)
                              // 调整光标到最后
                              quill.setSelection(length + 1)
                            })
                        })
                    })
                  })
                }
              }, 500)
              this.isLoading = false
            }).catch((err) => {
              this.isLoading = false
              message.error(err)
            })
          }).catch((err) => {
            this.isLoading = false
            message.error(err)
          })
        }
        return false
      },

      handleUpload2 (file) {
        // 校验文件
        if (file.size / 1024 / 1024 > 15) {
          const isRightSize = file.size / 1024 / 1024 < 15
          if (!isRightSize) {
            message.warning('文件大小超过 15MB')
          }
          return isRightSize
        } else {
          const from = {
            ClassId: process.env.NODE_ENV === 'production' ? 753706 : 790574
          }
          this.isLoading = true
          btnSignature(from).then((res) => {
            const getSignature = res.signature
            btnUpload3(getSignature, file).then((data) => {
              this.fullscreenLoading = false
              this.isLoading = false
              // 获取富文本组件实例
              const quill = this.$refs.QuillEditor.quill
              // 获取光标所在位置
              const length = quill.getSelection().index
              quill.insertEmbed(
                length,
                'audio', {
                  url: data.url,
                  name: file.name
                },
                'api'
              )
              quill.setSelection(length + 1) // 光标位置向后移动一位
            }).catch((err) => {
                this.isLoading = false
                message.error(err)
              })
          }).catch((err) => {
                this.isLoading = false
                message.error(err)
              })
        }
        return false
      }

      // 插入字符串
      // insertStr(soure, start, newStr) {
      //   return soure.slice(0, start) + newStr + soure.slice(start);
      //  }
    }
  }
</script>

<style lang="less" scoped>
	.com-quill-editor {
		margin-bottom: 40px;
		line-height: 2rem !important;
	}

	.sizeNumber {
		color: #e92300;
		line-height: 2rem !important;
	}
</style>
